package com.zmn.plat.services.impl.part;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.fileupload.FileUploadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.zmn.common.dto.ResultDTO;
import com.zmn.common.utils.file.FileTypeUtil;
import com.zmn.plat.business.interfaces.pic.PicUploadBService;
import com.zmn.plat.services.interfaces.part.PartImageUploadService;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author DaiZhichao
 * @version v1.0
 * @since 2019/2/15 10:40 类说明：PartImageUploadService实现类
 */
@Service
public class PartImageUploadServiceImpl implements PartImageUploadService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private PicUploadBService picUploadBService;

    @Override
    public String uploaderImage(MultipartFile file, String name, String path) throws FileUploadException {

        String fileExtension;

        ResultDTO uploadPicResultDTO;
        try {
            fileExtension = FileTypeUtil.getType(file.getInputStream()).getFileExtension();

            uploadPicResultDTO = picUploadBService.uploadPic(path, name + fileExtension, file.getInputStream());
            if (!uploadPicResultDTO.getStatusBool()) {
                throw new FileUploadException(uploadPicResultDTO.getMessage());
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new FileUploadException(e.getMessage());
        }
        return picUploadBService.getPicUrl(path, name + fileExtension);
    }

    @Override
    public String uploaderImage(File file, String name, String path) throws FileUploadException {
        ResultDTO uploadPicResultDTO;
        try {
            uploadPicResultDTO = picUploadBService.uploadPic(path, name, new FileInputStream(file));
            if (!uploadPicResultDTO.getStatusBool()) {
                throw new FileUploadException(uploadPicResultDTO.getMessage());
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new FileUploadException(e.getMessage());
        }
        return picUploadBService.getPicUrl(path, name);
    }
}
